package com.minelx.sqlstructures.common.parse;

import com.minelx.sequence.core.StringScanner;
import com.minelx.sequence.core.ReturnMatcher;

public class JoinMatcher<R> implements ReturnMatcher<R, StringScanner> {
	private final ReturnMatcher<String, StringScanner> joinerMatcher;

	private final ReturnMatcher<R, StringScanner> jewelMatcher;

	private boolean isFirstMatch;

	public JoinMatcher(ReturnMatcher<String, StringScanner> joinerMatcher, ReturnMatcher<R, StringScanner> jewelMatcher) {
		this.joinerMatcher = joinerMatcher;
		this.jewelMatcher = jewelMatcher;
		isFirstMatch = true;
	}

	@Override
	public R onMatched(StringScanner source) {
		// straight consume the jewel item if it's the first match
		if (isFirstMatch) {
			// make here never happens
			isFirstMatch = false;
			return jewelMatcher.onMatched(source);
		}
		// pass joiner
		joinerMatcher.onMatched(source);
		// pick the jewel
		return jewelMatcher.onMatched(source);
	}

	@Override
	public boolean isMatch(StringScanner source) {
		if (isFirstMatch) {
			return jewelMatcher.isMatch(source);
		}
		return joinerMatcher.isMatch(source);
	}
}
